package com.shu.auth.common;

import com.shu.auth.constants.Constant;
import com.shu.auth.utils.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 拦截器
 * 1、可以用于对接口的参数打印
 * 2、可以监控接口的执行时间
 */
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {
    /**
     * 请求之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url=request.getRequestURL().toString();
        Map parameterMap=request.getParameterMap();
        log.info("request start url:{} params:{}",url, JsonMapper.obj2String(parameterMap));
        long startTime = System.currentTimeMillis();
        request.setAttribute(Constant.REQUEST_START_TIME,startTime);
        return true;
    }

    /**
     *请求正常处理完成后调用的方法
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //效果与afterCompletion相同
        /*String url=request.getRequestURL().toString();
        long startTime =(Long)request.getAttribute(Constant.REQUEST_START_TIME);
        long endTime = System.currentTimeMillis();
        log.info("postHandle url:{} 接口耗时：{} 毫秒",url,endTime-startTime);*/

    }

    /**
     * 请求正常或者异常时之后都调用的方法
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url=request.getRequestURL().toString();
        long startTime =(Long)request.getAttribute(Constant.REQUEST_START_TIME);
        long endTime = System.currentTimeMillis();
        log.info("afterCompletion url:{} 接口耗时：{} 毫秒",url,endTime-startTime);

    }
}
